package service

import (
	"log"
	"testhttp/dao"
	"testhttp/model"
	"time"

	"github.com/kataras/iris/v12"
)

func ListRule(page, limit int) iris.Map {

	rules, err := dao.ListRule(page, limit)
	count := dao.CountRules()
	if err != nil {
		response := iris.Map{
			"code": 1,
			"msg":  err,
		}
		return response
	} else {
		res := make([]model.ListMapRules, len(rules))
		for x := 0; x < len(rules); x++ {
			res[x].RuleName = rules[x].RuleName
			res[x].RuleUid = rules[x].RuleUid
			dealer, _ := GetDealerbyId(rules[x].DealerId)
			if len(dealer) == 0 {
				res[x].Dealer = "null"
			} else {
				res[x].Dealer = dealer[0].Dealer
			}

		}

		response := iris.Map{
			"code":  0,
			"msg":   "OK",
			"count": count,
			"data":  res,
		}
		log.Print("Debug service listrule:", count, res, rules)
		return response
	}

}

func AddRule(rule []model.MapRules) iris.Map {
	now := time.Now()
	var query []model.MapRules
	for x := 0; x < len(rule); x++ {
		if rule[x].ImpHead == "" || rule[x].ImpHead == "default" || rule[x].ExpHead == "" || rule[x].ExpHead == "default" {

		} else {
			rule[x].CreateTime = now
			rule[x].UpdateTime = now
			rule[x].IsDeleted = 0
			query = append(query, rule[x])
		}
	}
	r, err := dao.InsertRules(query)
	if err != nil {
		res := iris.Map{
			"code": 1,
			"msg":  err,
		}
		return res
	} else {
		res := iris.Map{
			"code":    0,
			"success": r,
		}
		return res
	}
}
